#include "c_cache.h"
#include <pthread.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

struct TRingBuf *Buf = NULL; 
void* Write(void *reg) {
    char r[] = "qwertyuiopasdfghjklzxcvbnm";
    TRingBufWrite(Buf, r, 26);
    printf("*****************************\n");
    printf("First Write success!!\n");
    printf("The data_size is %d\n",TRingBufDataSize(Buf));
    printf("The free_size is %d\n",TRingBufFreeSize(Buf));
    printf("The data of buf is :%s\n", Buf->buf);
    sleep(1);
    char s[] = "qwertyuiopasdfghjklzxcvbnm";
    TRingBufWrite(Buf, s, 26);
    printf("*****************************\n");
    printf("Second Write success!!\n");
    printf("The data_size is %d\n",TRingBufDataSize(Buf));
    printf("The free_size is %d\n",TRingBufFreeSize(Buf));
    printf("The data of buf is :%s\n", Buf->buf);
    return NULL; 
}
void* Read(void *reg) {
    char *buf = (char *)malloc(16*sizeof(char));
    TRingBufRead(Buf, buf, 16);
    printf("*****************************\n");
    printf("The result of reading is :%s\n", buf);
    free(buf);
    buf = NULL;
    printf("The data_size is %d\n",TRingBufDataSize(Buf));
    printf("The free_size is %d\n", TRingBufFreeSize(Buf));
    sleep(0.5);
    buf = (char *)malloc(16*sizeof(char));
    TRingBufRead(Buf, buf, 16);
    printf("*****************************\n");
    printf("The result of reading is :%s\n", buf);
    free(buf);
    buf = NULL;
    return NULL;
}
int main() {
    pthread_t tid[2];
    Buf = (struct TRingBuf*)malloc(sizeof(struct TRingBuf));
    char str[] = "12345678901234567890123456789012345";
    TRingBufCreate(Buf, str, 35);
    printf("*****************************\n");
    printf("The circle_cache is created!!\n");
    printf("The data_size is %d\n",TRingBufDataSize(Buf));
    printf("The free_size is %d\n", TRingBufFreeSize(Buf));
    sleep(0.01);
    int ret = pthread_create(&tid[0], NULL, Write, NULL);
    if(ret != 0) printf("pthread create fail\n");
    usleep(0.0001);
    int re = pthread_create(&tid[1], NULL, Read, NULL);
    if(re != 0) printf("pthread create fail\n");
    sleep(3);
    TRingBufClear(Buf);
    free(Buf);
    Buf = NULL;
    return 0;
}
